//
//  LBStatisticsModel.m
//  LBStatistics
//
//  Created by WuShiHai on 19/5/24.
//  Copyright (c) 2019 Lebbay. All rights reserved.
//

#import "LBStatisticsModel.h"
#import "FMDatabaseQueue.h"
#import "FMDatabase.h"

#define __String_Not_Nil(str) (str?:@"")

//统计记录的数据库
#define kStatisticsDBName @"statistics-ext.sqlite"

@interface LBStatisticsModel ()

@property (nonatomic, strong) FMDatabaseQueue *databaseQueue;

@end


@implementation LBStatisticsModel

static LBStatisticsModel *instance = nil;
+ (instancetype)sharedInstance{
    if (instance == nil) {
        instance =[[LBStatisticsModel alloc] init];
    }
    return instance;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        [self connectDB];
        [self createStatisticsTable];
        
    }
    return self;
}

- (void)connectDB{
    // 沙盒Docu目录
    NSString * documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
    NSString *dbPath = [documentDirectory stringByAppendingString:[NSString stringWithFormat:@"/%@",kStatisticsDBName]];
    NSFileManager * fileManager = [NSFileManager defaultManager];
    BOOL isExist = [fileManager fileExistsAtPath:dbPath];
    if (!isExist) {
        [fileManager createFileAtPath:dbPath contents:nil attributes:nil];
    }
    self.databaseQueue = [FMDatabaseQueue databaseQueueWithPath:dbPath];
}

#pragma mark - 创建表
//创建统计日志表
- (void)createStatisticsTable{
    NSString *sql = @"create table if not exists StatisticsLog(identifier INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,url text,params text,failcount integer,type INTEGER,action text, createtime timestamp not null default (datetime('now','localtime')))";
   [self.databaseQueue inDatabase:^(FMDatabase *db) {
       [db executeUpdate:sql];
   }];
}
#pragma mark - 数据更新

- (NSInteger)insertOneStatistics:(LBStatisticsTaskData *)task{
    __block NSInteger identitifer = -1;
    NSString *sql = [NSString stringWithFormat:@"insert or replace into StatisticsLog (url,params,failcount,type,action) values (?,?,?,?,?)"];
    [self.databaseQueue inDatabase:^(FMDatabase *db) {
        BOOL isSuccess = [db executeUpdate:sql,
         __String_Not_Nil(task.url),
         __String_Not_Nil(task.params),
         [NSNumber numberWithInteger:task.failCount],
         [NSNumber numberWithInteger:task.type],
         __String_Not_Nil(task.action)
         ];
        if (isSuccess) {
             identitifer = [db lastInsertRowId];
        }
    }];
    return identitifer;
}



- (NSArray *)queryAllStatistics{
    __block NSMutableArray *resultArray = [NSMutableArray array];
 
    [self.databaseQueue inDatabase:^(FMDatabase *db) {
        NSString *sql = @"select * from StatisticsLog  where type = 1  order by failcount asc limit 0, 1000";
        FMResultSet *resultSet = [db executeQuery:sql];
        while ([resultSet next]) {
            NSInteger identifier = [resultSet intForColumn:@"identifier"];
            NSString *url = [resultSet stringForColumn:@"url"];
            NSString *params = [resultSet stringForColumn:@"params"];
            NSInteger failCount = [resultSet intForColumn:@"failcount"];
            NSInteger type = [resultSet intForColumn:@"type"];
            NSString *action = [resultSet stringForColumn:@"action"];
            LBStatisticsTaskData *task = [[LBStatisticsTaskData alloc] initWithURL:url params:params type:type action:action];
            task.taskIdentifier = identifier;
            task.failCount = failCount;
            [resultArray addObject:task];
        }
        [resultSet close];
    }];
    return [resultArray copy];
}

- (BOOL)updateStatisticsDataFailCount:(NSArray *)taskDatas{
    
    __block BOOL isSuccess = NO;
    [self.databaseQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        for (LBStatisticsTaskData *taskData in taskDatas){
            NSString *sql = [NSString stringWithFormat:@"update StatisticsLog set failcount = ? where identifier = ?"];
         
            isSuccess = [db executeUpdate:sql,
                         [NSNumber numberWithInteger:taskData.failCount],
                         [NSNumber numberWithInteger:taskData.taskIdentifier]
                         ];
            if (!isSuccess) {
                *rollback = YES;
                break;
            }
         

        }
    }];
    return isSuccess;
}

- (BOOL)removeStatistics:(NSArray *)taskIdentifiers{
    
    __block BOOL isSuccess = NO;
    NSString *sql = [NSString stringWithFormat:@"delete from StatisticsLog where identifier = ?"];
    
    [self.databaseQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        for (NSNumber *number in taskIdentifiers){
        
            if (number.integerValue == 0) {
                continue;
            }
            
            isSuccess = [db executeUpdate:sql,
                             number
                             ];
            if (!isSuccess) {
                *rollback = YES;
                break;
            }
        }
    }];
    return isSuccess;
}

- (NSDictionary *)deleteLongLongAgoLogs{
    
    __block NSMutableDictionary *resultDict = [NSMutableDictionary dictionary];
    [self.databaseQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        //查询一天以前的
         NSString *sql = @"select action, count(*) count from StatisticsLog where createtime <= datetime('now','localtime','-1 day') group by action";
        
         FMResultSet *resultSet = [db executeQuery:sql];
        while ([resultSet next]) {
            NSString *action = [resultSet stringForColumn:@"action"];
            NSInteger count = [resultSet intForColumn:@"count"];
            if (action.length > 0) {
                 [resultDict setObject:@(count) forKey:action];
            }
        }
        
        [resultSet close];
        
        // 删除历史的
        sql = @"delete from StatisticsLog where createtime <= datetime('now','localtime','-1 day')";

        [db executeUpdate:sql];
    }];
    return [resultDict copy];
}
@end
